package com.woniuxy.dao.impl;

import com.woniuxy.dao.UserDao;
import com.woniuxy.entity.User;

import java.io.*;

/**
 * 学生数据操作的实现类，使用文件实现
 */
public class UserDaoImpl implements UserDao {
    @Override
    public User getUserByUname(String uname) {
        User user = null;
        BufferedReader br=null;
        try{
            br=new BufferedReader(new FileReader("d:\\user.txt"));
            String line=null;
            while ((line=br.readLine())!=null){
                String[] strings = line.split(",");
                if(strings[1].equals(uname)){
                    user=new User();
                    user.setUid(strings[0]);
                    user.setUname(strings[1]);
                    user.setPassword(strings[2]);
                    user.setAge(Integer.valueOf(strings[3]));
                    user.setEmail(strings[4]);
                    break;
                }
            }
            return user;
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            try {
                if (br!=null) {
                    br.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void addUser(User user) {
        try{
            BufferedWriter bw=
                    new BufferedWriter(new FileWriter("d:\\user.txt",true));
            bw.write(user.getUid()+","+user.getUname()+","
                    +user.getPassword()+","+user.getAge()+","+user.getEmail());
            bw.newLine();
            bw.flush();
            bw.close();
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getMaxUid() {
        try {
            String maxUid="0";
            BufferedReader br=new BufferedReader(new FileReader("d:\\user.txt"));
            String line=null;
            while ((line=br.readLine())!=null){
                String[] strings = line.split(",");
                maxUid=strings[0];
            }
            return maxUid;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
